package cn.itcast.service.system.impl;

import cn.hutool.core.util.IdUtil;
import cn.itcast.dao.system.UserDao;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    //依赖注入
    @Autowired
    private UserDao userDao;

    @Override
    public List<User> findAll(String companyId) {
        return userDao.findAll(companyId);
    }

    @Override
    public User findById(String id) {
        return userDao.findById(id);
    }

    @Override
    public void save(User user) {
        //需要添加主键
        user.setId(IdUtil.simpleUUID());
        userDao.save(user);
    }

    @Override
    public void update(User user) {
        //修改
        userDao.update(user);
    }

    @Override
    public void delete(String id) {
        //删除
        userDao.delete(id);
    }

    @Override
    public PageInfo findByPage(Integer pageNum, Integer pageSize, String companyId) {
        //分页
        //开启分页
        PageHelper.startPage(pageNum,pageSize);
        //调用方法
        List<User> list = userDao.findAll(companyId);
        //封装对象
        return new PageInfo(list);
    }

    @Override
    public List<String> findRoleIdListByUserId(String id) {
        //调用dao中的方法
        return userDao.findRoleIdListByUserId(id);
    }

    @Override
    public void changeRole(String userId, String[] roleIds) {
        //根据用户id删除中间表
        userDao.deleteRoleIdsByUserId(userId);
        //遍历角色数组,重新添加中间表数据
        if (roleIds!=null && roleIds.length>0){
            for (String roleId : roleIds) {
                //调用添加方法
                userDao.saveRoleIdAndUserId(userId,roleId);
            }
        }
    }

    @Override
    public User findByEmail(String email) {
        //调用dao
        return userDao.findByEmail(email);
    }
}
